package com.yj.timecapsule.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author Sean
 * @CreateTime 2024-08-05  11:40
 * @Description
 * @Version 1.0
 */
@Configuration
public class ThreadPoolConfig {
    private static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors() + 1;
    private static final int MAX_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2 + 1;
    private static final int WORK_QUEUE_SIZE = 1000;
    private static final int KEEP_ALIVE_TIME = 60;
    @Bean("websocketExecutor")
    public ThreadPoolTaskExecutor websocketExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setQueueCapacity(WORK_QUEUE_SIZE);
        executor.setThreadNamePrefix("websocket-call-");
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.setKeepAliveSeconds(KEEP_ALIVE_TIME);
        executor.initialize();
        return executor;
    }
    @Bean("smsExecutor")
    public ThreadPoolTaskExecutor smsExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setQueueCapacity(WORK_QUEUE_SIZE);
        executor.setThreadNamePrefix("sms-executor-");
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.setKeepAliveSeconds(KEEP_ALIVE_TIME);
        executor.initialize();
        return executor;
    }
    @Bean("databaseExecutor")
    public ThreadPoolTaskExecutor databaseExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setQueueCapacity(WORK_QUEUE_SIZE);
        executor.setThreadNamePrefix("database-");
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.setKeepAliveSeconds(KEEP_ALIVE_TIME);
        executor.initialize();
        return executor;
    }
}
